import router, {
	routes
} from '@/router';
import store from '@/store';
import VueCookies from 'vue-cookies';
import {
	Message
} from 'element-ui';
import {
	reqInstallCheck
} from '@/api';

const filterRoutes = (routes, arr = [], path = '') => {
	for (let route of routes) {
		if (path && path !== '/') {
			arr.push(`${path}/${route.path}`);
		} else if (path === '/') {
			arr.push(`/${route.path}`);
		} else {
			arr.push(`${route.path}`);
		}
		if (route.children && route.children.length) {
			filterRoutes(route.children, arr, route.path)
		}
	}
	return arr;
}

const filterMenus = (menus, arr = []) => {
	for (let menu of menus) {
		arr.push(menu.url);
		if (menu.group && menu.group.length) {
			filterMenus(menu.group, arr)
		}
	}
	return arr;
}

router.beforeEach(async (to, from, next) => {
	const {
		data
	} = await reqInstallCheck({});
	if (data.check_status === 1) {
		let loToken = localStorage.getItem('token');
		let coToken = VueCookies.get('token');
		if (to.path === '/install') {
			return false;
		} else {
			if (loToken && coToken) {
				if (to.path === '/login') {
					return false;
				} else {
					const menus = store.state.menus;
					if (menus.length) {
						next();
					} else {
						await store.dispatch('getMenus');
						next({
							...to,
							replace: true
						})
					}
				}
			} else {
				if (to.path === '/login') {
					next();
				} else {
					next('/login');
				}
			}
		}
	} else {
		if (to.path === '/install') {
			localStorage.clear();
			next();
		} else {
			next('/install')
		}
	}
});
